package cn.zh.npro.Fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.zh.npro.Activity.AddClient;
import cn.zh.npro.Activity.Client;
import cn.zh.npro.Activity.CsActivity;
import cn.zh.npro.Adapter.CeAdapter;
import cn.zh.npro.Adapter.CfAdapter;
import cn.zh.npro.Adapter.CrAdapter;
import cn.zh.npro.Adapter.CtAdapter;
import cn.zh.npro.Item.CfItem;
import cn.zh.npro.Item.ClevItem;
import cn.zh.npro.Item.CrItem;
import cn.zh.npro.Item.CtItem;
import cn.zh.npro.MyApplication;
import cn.zh.npro.R;
import cn.zh.npro.Util.BaseUrl;
import cn.zh.npro.Util.Loading;
import cn.zh.npro.Util.MyListener;
import cn.zh.npro.Util.PullToRefreshLayout;
import cn.zh.npro.Util.PullableListView;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by WYN on 2018/2/26 0026.
 */

public class ClientFragment extends Fragment implements PullableListView.OnLoadListener, View.OnClickListener {
    PullableListView cpulist;
    PullToRefreshLayout crefresh_view;
    //暂无数据
    TextView cempty;
    int page=1;
    MyApplication mapp;
    String uid;
    ArrayList<CfItem> cfItems=new ArrayList<CfItem>();
    CfAdapter cfAdapter=null;
    ImageView cseleimg,wima;
    PopupWindow popupWindow;
    int type=0;
    CtAdapter ctAdapter;
    CeAdapter ceAdapter;
    CrAdapter crAdapter;
    TextView cuslevel,custype,stxt;
    ArrayList<ClevItem> clevItems=new ArrayList<>();
    ArrayList<CtItem> ctItems=new ArrayList<>();
    ArrayList<CrItem>crItems=new ArrayList<>();
    ClevItem clevItem=null;
    CtItem ctItem=null;
    CrItem crItem = null;
    ImageView adclient;
    LinearLayout cslin;
    String key="";
    public static final int INIT = 0;
    public static final int STOP = 2;
    private Dialog LDialog;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.cl_layout,container,false);
        mapp= (MyApplication) getActivity().getApplication();
        uid=mapp.getSp().getString("uid","");
        initcf(view);
//        getClient(page+"");
        return view;
         }



    public void initcf(View view){
        crefresh_view=(PullToRefreshLayout)view.findViewById(R.id.crefresh_view);
        cempty= (TextView)view.findViewById(R.id.cempty);
        stxt = view.findViewById(R.id.stxt);
        cseleimg= view.findViewById(R.id.cseleimg);
        wima= view.findViewById(R.id.wima);
        adclient= view.findViewById(R.id.adclient);
        cslin= view.findViewById(R.id.cslin);
        cpulist= (PullableListView)view.findViewById(R.id.cpulist);
        cfAdapter=new CfAdapter(getActivity(),cfItems,mapp);
        cpulist.setAdapter(cfAdapter);
        cpulist.setOnLoadListener(this);
        cseleimg.setOnClickListener(this);
        adclient.setOnClickListener(this);
        cslin.setOnClickListener(this);
        wima.setOnClickListener(this);
        crefresh_view.setOnRefreshListener(new MyListener(){
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                super.onRefresh(pullToRefreshLayout);
                //下拉刷新
                page=1;
                getClient(page+"");
              }
            });

        cpulist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent1=new Intent(getActivity(),Client.class);
                intent1.putExtra("clId",cfItems.get(i).getId());
                intent1.putExtra("type","cftype");
                startActivity(intent1);
            }
        });
        }


    @Override
    public void onLoad(PullableListView pullableListView) {
        page=page+1;
        getClient(page+"");
        }

    @Override
    public void onResume() {
        super.onResume();
        clevItem=null;
        crItem=null;

        getClient(page+"");

        }

    @Override
    public void onClick(View view) {
        int id=view.getId();
        switch (id){
            case R.id.cseleimg:
                showPopUp();
                break;
            case R.id.claslin:
                //客户类型\
                type=0;
                getPo();
                getGetCustomerClass();
                break;
            case R.id.clvelin:
                //客户等级
                type=1;
                getPo();
                initcls();
                break;
            case R.id.gasure:
                popupWindow.dismiss();
                getClient(page+"");
                break;
            case R.id.clean:
                crItem=null;
                clevItem=null;
                popupWindow.dismiss();
                getClient(page+"");
                break;
            case R.id.adclient:
                //添加客户
                Intent intent=new Intent(getActivity(),AddClient.class);
                startActivity(intent);
                break;
            case R.id.cslin:
             Intent intent1=new Intent(getActivity(),CsActivity.class);
             startActivityForResult(intent1,0);
             break;
            case R.id.wima:
                stxt.setText("客户名称");
                key="";
                page=1;
                getClient(page+"");
                wima.setVisibility(View.GONE);
                break;
            case R.id.poview:
                popupWindow.dismiss();
                break;
            }
          }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case 1:
                String name=data.getStringExtra("name");
                key=name;
                stxt.setText(name);
                page=1;
                getClient(page+"");
                wima.setVisibility(View.VISIBLE);
               break;
               }
             }


    public void getClient(final String page){
        String lv="",ty="";
        if (null!=clevItem){
            lv=clevItem.getCustomerLevelId();
         }
       if (null!=crItem){
           ty=crItem.getClassID();
          }

        OkHttpUtils.get(BaseUrl.GetCustomerList)
                .params("pageIndex",page)
                .params("pageSize","6")
                .params("userId",uid)
                .params("key",key)
                .params("level",lv)
                .params("state","")
                .params("customerType",ty)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        if (null!=LDialog){
                            Loading.closeDialog(LDialog);
                          }
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                JSONArray Res=js.getJSONArray("Res");
                                if (page.equals("1")){
                                    cfItems.clear();
                                    if (0==Res.length()){
                                        cempty.setVisibility(View.VISIBLE);
                                        crefresh_view.setVisibility(View.INVISIBLE);
                                        cpulist.finishLoading(INIT);
                                        return;
                                    }else {
                                        cempty.setVisibility(View.GONE);
                                        crefresh_view.setVisibility(View.VISIBLE);
                                      }
                                  }else {
                                    if (0==Res.length()){
                                        cpulist.finishLoading(STOP);
                                        return;
                                     }
                                  }
                                for (int i=0;i<Res.length();i++){
                                    JSONObject ji=Res.getJSONObject(i);
                                    String id=ji.getString("ID");
                                    String companyName=ji.getString("companyName");
                                    String customerLevel=ji.getString("CustomerLevel");
                                    String address=ji.getString("address");
                                    CfItem cfItem=new CfItem(id,companyName,customerLevel,address);
                                    cfItems.add(cfItem);
                                   }
                                 cfAdapter.notifyDataSetChanged();
                               }else {
                                cempty.setVisibility(View.VISIBLE);
                                crefresh_view.setVisibility(View.GONE);
                              }
                            cpulist.finishLoading(INIT);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                      }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
            }



    //侧滑弹窗
    private void showPopUp() {
        View vp = LayoutInflater.from(getActivity()).inflate(R.layout.cfpop, null, false);

        Button gasure=vp.findViewById(R.id.gasure);
        Button clean=vp.findViewById(R.id.clean);
        custype=vp.findViewById(R.id.custype);
        cuslevel = vp.findViewById(R.id.cuslevel);
        if (null!=crItem){
            custype.setText(crItem.getClassName());
          }else {
            custype.setText("全部");
         }
        if (null!=clevItem){
            cuslevel.setText(clevItem.getCustomerLevelTitle());
        }else {
            cuslevel.setText("全部");
          }
        LinearLayout  claslin=vp.findViewById(R.id.claslin);
        LinearLayout  clvelin=vp.findViewById(R.id.clvelin);
        View  poview=vp.findViewById(R.id.poview);
        gasure.setOnClickListener(this);
        clean.setOnClickListener(this);
        claslin.setOnClickListener(this);
        clvelin.setOnClickListener(this);
        poview.setOnClickListener(this);
        WindowManager wm = (WindowManager) getActivity()
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        int  mScreenWitdh = outMetrics.widthPixels;
        int  mhright = outMetrics.heightPixels;

        popupWindow = new PopupWindow(vp, LinearLayout.LayoutParams.MATCH_PARENT, mhright);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        popupWindow.setClippingEnabled(false);
        popupWindow.setAnimationStyle(R.style.popwin_anim_style);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        popupWindow.showAtLocation(getActivity().findViewById(R.id.cl_layout), Gravity.NO_GRAVITY, 0, 0);
        }





    public void getPo(){
        View vpa = LayoutInflater.from(getActivity()).inflate(R.layout.gaa_layout, null, false);
        WindowManager wm = (WindowManager) getActivity()
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        int  mScreenWitdh = outMetrics.widthPixels;
        int lweith=mScreenWitdh/5;
        final ImageView gaa=vpa.findViewById(R.id.gaa_back);

        ListView gaa_list=vpa.findViewById(R.id.gaa_list);
        TextView tittxt=vpa.findViewById(R.id.tittxt);

        switch (type){
            case 0:
                tittxt.setText("类型");
                String txt1=custype.getText().toString();
                crAdapter = new CrAdapter(getActivity(),crItems,txt1);
                gaa_list.setAdapter(crAdapter);
                break;
            case 1:
                tittxt.setText("客户级别");
                String txt=cuslevel.getText().toString();
                ceAdapter = new CeAdapter(getActivity(),clevItems,txt);
                gaa_list.setAdapter(ceAdapter);
                break;
             }
        final PopupWindow popupWindowga = new PopupWindow(vpa, mScreenWitdh-lweith, LinearLayout.LayoutParams.MATCH_PARENT);
        gaa_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
               if (type==0){
                   crItem=crItems.get(i);
                   custype.setText(crItem.getClassName());
               }else {
                   clevItem=clevItems.get(i);
                   cuslevel.setText(clevItem.getCustomerLevelTitle());
                 }
                popupWindowga.dismiss();
              }
           });

        popupWindowga.setFocusable(true);
        popupWindowga.setOutsideTouchable(true);
        popupWindowga.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindowga.getContentView().setFocusableInTouchMode(true);
        popupWindowga.getContentView().setFocusable(true);
        popupWindowga.setAnimationStyle(R.style.popwin_anim_style);
        gaa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindowga.dismiss();
            }
        });

        popupWindowga.showAtLocation(getActivity().findViewById(R.id.cl_layout), Gravity.NO_GRAVITY, lweith, 0);
        }




    public void initcls(){
        OkHttpUtils.get(BaseUrl.GetCustomerLevel)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                JSONArray Res=js.getJSONArray("Res");
                                clevItems.clear();
                                ClevItem clevIte=new ClevItem("","","全部","","");
                                clevItems.add(clevIte);
                                for (int i=0;i<Res.length();i++){
                                    JSONObject ji=Res.getJSONObject(i);
                                    String customerLevelId=ji.getString("customerLevelId");
                                    String customerLevel=ji.getString("customerLevel");
                                    String customerLevelTitle=ji.getString("customerLevelTitle");
                                    String days=ji.getString("days");
                                    String sortOrder=ji.getString("sortOrder");
                                    ClevItem clevItem=new ClevItem(customerLevelId,customerLevel,customerLevelTitle,days,sortOrder);
                                    clevItems.add(clevItem);
                                }
                                ceAdapter.notifyDataSetChanged();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
              }



    public void getGetCustomerClass(){
        OkHttpUtils.get(BaseUrl.GetCustomerClass)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                JSONArray Res=js.getJSONArray("Res");
                                crItems.clear();
                                for (int i=0;i<Res.length();i++){
                                    JSONObject ji=Res.getJSONObject(i);
                                    String ClassID=ji.getString("ClassID");
                                    String ClassName=ji.getString("ClassName");
                                    String OrderPos=ji.getString("OrderPos");
                                    String bBlockUp=ji.getString("bBlockUp");
                                    CrItem crItem= new CrItem(ClassID,ClassName,OrderPos,bBlockUp);
                                    crItems.add(crItem);
                                }
                                crAdapter.notifyDataSetChanged();

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }


  }
